######################
##### PREPARATION ####
######################
rm(list=setdiff(ls(), "path_to"))

# Load data
s = readRDS(path_to("wide"))
s_robust = readRDS(path_to("robustness_beliefs"))
coded = readRDS(path_to("coded"))
coded_conseq = readRDS(path_to("coded_conseq"))


#######################
##### MERGE ###########
#######################
# Test: Coded data complete
if (any(!s$ResponseId %in% coded$ResponseId)) {warning("Coded data incomplete.")}
if (any(!s$ResponseId %in% coded_conseq$ResponseId)) {warning("Coded data incomplete.")}
if (any(!s_robust$ResponseId %in% coded$ResponseId)) {warning("Coded data incomplete.")}

# Merge
s = s %>% left_join(coded[, c("ResponseId", "code_effect", "code_effect_simple")], by="ResponseId")
s = s %>% left_join(coded_conseq[, c("ResponseId", "code_conseq", "code_conseq_simple")], by="ResponseId")
s_robust = s_robust %>% left_join(coded[, c("ResponseId", "code_effect", "code_effect_simple")], by="ResponseId")

# Define new variables
s$explanation_dampening = 1*(s$code_effect_simple == "dampening")
s$explanation_conseq_strict = 1*(grepl("conseq", s$code_conseq_simple) & !grepl("deont", s$code_conseq_simple))
s$explanation_conseq_weak = 1*(grepl("conseq", s$code_conseq_simple))


#######################
##### EXPORT ##########
#######################
saveRDS(s, path_to("wide"))
saveRDS(s_robust, path_to("robustness_beliefs"))
